package com.tobby.demo.jaxbdemo;

import java.io.File;
import java.util.HashSet;
import java.util.Set;

import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;
import javax.xml.bind.Unmarshaller;

import com.tobby.demo.jaxb.entity.Book;
import com.tobby.demo.jaxb.entity.Customer;

public class JaxbDemo {
	public static void main(String[] args) throws JAXBException {
		Customer customer = new Customer(100, "Tobby Li", 29);
		Set<Book> books = new HashSet<Book>();
		books.add(new Book(1, "HarryPorter", 45));
		books.add(new Book(2, "苹果", 50));
		customer.setBooks(books);
		JaxbDemo jaxbDemo = new JaxbDemo();
		jaxbDemo.object2Xml(customer);
		// jaxbDemo.xml2Object();
	}

	private void object2Xml(Customer customer) throws JAXBException {
		File file = new File("C:/Users/ll00252/file1.xml");
		JAXBContext jc = JAXBContext.newInstance(Customer.class);
		Marshaller marshaller = jc.createMarshaller();
		marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
		marshaller.marshal(customer, file);
		marshaller.marshal(customer, System.out);
	}

	@SuppressWarnings("unused")
	private void xml2Object() throws JAXBException {
		File file = new File("C:/Users/ll00252/file1.xml");
		JAXBContext jc = JAXBContext.newInstance(Customer.class);
		Unmarshaller unmarshaller = jc.createUnmarshaller();
		Customer customer = (Customer) unmarshaller.unmarshal(file);
		System.out.println(customer);
	}
}
